package com.atguigu.gmall.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.util.IpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import org.yaml.snakeyaml.events.Event;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author :ttm
 * @description :
 * @create :2021-12-27 10:20:00
 */
@Component
public class AuthGlobalFilter implements GlobalFilter {
    @Value("${authUrls.url}")
    public String authUrls;//trade.html,myOrder.html,#list.html,#addCart.html

    @Autowired
    private RedisTemplate redisTemplate;
    //  声明一个匹配工具类
    private AntPathMatcher antPathMatcher = new AntPathMatcher();
    /**
     *
     * @param exchange 服务器web对象
     * @param chain 过滤器链对象
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //先获取用户请求路径
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        if (antPathMatcher.match("/**/inner/**",path)){
            //服务器响应
            ServerHttpResponse response = exchange.getResponse();
            //信息提示
           return outMsg(response, ResultCodeEnum.PERMISSION);
        }


        //编写一个获取用户id的方法 userid在缓存 key
            String userId=this.getUserId(request);
        //获取临时用户id
        String userTempId=this.getuserTempId(request);
        if ("-1".equals(userId)){
            ServerHttpResponse response = exchange.getResponse();
           return outMsg(response,ResultCodeEnum.PERMISSION);
        }
        if (antPathMatcher.match("/api/**/auth/**", path)){
            //判断用户是否登录
            if (StringUtils.isEmpty(userId)){
                //服务器响应
                ServerHttpResponse response = exchange.getResponse();
                //信息提示
                return outMsg(response,ResultCodeEnum.LOGIN_AUTH);
            }
        }
        //  用户在访问需要登录的业务模块时，必须要登录！ addToCart.html ,myOrder.html!
        //  判断 用户请求路径中是否包含  {trade.html,myOrder.html,list.html} 中控制器，如果包含，则需要判断用户是否登录！
        //  如果没有登录，则跳转到登录页面！
        String[] split = authUrls.split(",");
        if (split!=null&&split.length>0){
            for (String url : split) {
                //path 包含上述url，并且未登录，则需要跳转到登录页面
                if (path.contains(url)&& StringUtils.isEmpty(userId)){
                    //便些跳转登录页面
                    //获取响应
                    ServerHttpResponse response = exchange.getResponse();
                    //设置重定向
                    response.setStatusCode(HttpStatus.SEE_OTHER);
                    response.getHeaders().set(HttpHeaders.LOCATION,"http://www.gmall.com/login.html?originUrl="+request.getURI());
                    //重定向
                    return response.setComplete();
                }
            }
        }
        //判断userid是否为空，不为空放入请求头
        if (!StringUtils.isEmpty(userId) || !StringUtils.isEmpty(userTempId)){
            if (!StringUtils.isEmpty(userId)){
                request.mutate().header("userId",userId).build();
            }
            if (!StringUtils.isEmpty(userTempId)){
                request.mutate().header("userTempId",userTempId).build();
            }
            //ServerHttpRequest request
             request.mutate().header("userId", userId).build();
             //request--->exchange
             return chain.filter(exchange.mutate().request(request).build());

        }
        return chain.filter(exchange);
    }

    /**
     * 获取临时用户id
     * @param request
     * @return
     */
    private String getuserTempId(ServerHttpRequest request) {
        //userTempId在cookie中
        String userTempId="";
        HttpCookie httpCookie = request.getCookies().getFirst("userTempId");
        if (httpCookie!=null){
            userTempId = httpCookie.getValue();
        }else {
            List<String> stringList = request.getHeaders().get("userTempId");
            if (!CollectionUtils.isEmpty(stringList)){
                userTempId=stringList.get(0);
            }
        }
        return userTempId;
    }

    /**
     * 用户信息提示
     * @param response
     * @param resultCodeEnum
     * @return
     */
    private Mono<Void> outMsg(ServerHttpResponse response, ResultCodeEnum resultCodeEnum) {
        //输出的信息是什么
        Result<Object> result = Result.build(null, resultCodeEnum);
        //将result变为可输出数据
        String str = JSON.toJSONString(result);
        //构建数据流
        DataBuffer wrap = response.bufferFactory().wrap(str.getBytes());
        //设置请求头
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");


        return response.writeWith(Mono.just(wrap));
    }

    /**
     * 获取用户id
     * @param request
     * @return
     */
    private String getUserId(ServerHttpRequest request) {
        //获取userid:redis
        //必须先获取token
        //获取token 从header中取
        String token="";
        List<String> stringList = request.getHeaders().get("token");
        if (!CollectionUtils.isEmpty(stringList)){
            token=stringList.get(0);
        }else {
            HttpCookie httpCookie = request.getCookies().getFirst("token");
            if (httpCookie!=null){
                token=httpCookie.getValue();
            }
        }
        if (!StringUtils.isEmpty(token)){
            
            String loginKey="user:login:"+token;
            String  strJson =(String) redisTemplate.opsForValue().get(loginKey);
            JSONObject jsonObject = JSONObject.parseObject(strJson);
            String ip = (String)jsonObject.get("ip");
            if (ip.equals(IpUtil.getGatwayIpAddress(request))){
                //判断ip 地址是否一致
                String userId = (String)jsonObject.get("userId");
                return  userId;
            }else {
                return "-1";
            }
        }

        return "";
    }


}
